package com.dqp.cslggroup.SubjectView;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.StringUtil;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.Util.UiUtils;
import com.dqp.cslggroup.bean.course;

import org.greenrobot.eventbus.EventBus;

import java.util.Objects;

import cn.carbswang.android.numberpickerview.library.NumberPickerView;

public class AddCourse extends BaseActivity {
    private EditText couese_name, course_room, course_tearch;
    private TextView add_course;
    private boolean dan = false, all = true, shuang = false, edit = false;
    private int[] flag = new int[20];
    private TextView et_weeks, et_time;
    private course course = new course();
    private boolean couples;

    @SuppressLint("SetTextI18n")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_course);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        initCmp();
        Intent intent = getIntent();
        edit = intent.getBooleanExtra("edit", false);
        couples = intent.getBooleanExtra("couples", true);
        if (edit) {
            course = (com.dqp.cslggroup.bean.course) intent.getSerializableExtra("course");
            if (course != null) {
                if (course.getZcd() != null && course.getZcd().length() > 0) {
                    int[] weeks = StringUtil.SelectNumber(SubjectRepertory.getWeekList(course.getZcd()).toString());
                    for (int i = 0; i < flag.length; i++) {
                        flag[i] = 1;
                        for (int value : weeks) {
                            if (i == value - 1) flag[i] = 0;
                        }
                    }
                }
                if (course.getXnm() != null && course.getXnm().length() > 0) {
                    couese_name.setText(course.getKcmc());
                    course_room.setText(course.getCdmc());
                    course_tearch.setText(course.getXm());
                    et_weeks.setText(course.getZcd());
                    et_time.setText(course.getXqjmc() + " " + course.getJc());

                }
            }
            add_course.setText("修改");
        }
        add_course.setOnClickListener(view -> {
            UiUtils.hideKeyboard(view);
            toaddCourse();
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @SuppressLint("SetTextI18n")
    public void initCmp() {
        couese_name = findViewById(R.id.et_name);
        course_room = findViewById(R.id.et_room);
        course_tearch = findViewById(R.id.et_teacher);
        add_course = findViewById(R.id.add_course_buttom);
        et_weeks = findViewById(R.id.et_weeks);
        et_time = findViewById(R.id.et_time);
        et_time.setOnClickListener(v -> {
            String[] weeks = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
            Dialog dialog;
            SharedPreferences sp;
            SharedPreferences.Editor editor;
            sp = PreferenceManager.getDefaultSharedPreferences(this);
            editor = sp.edit();
            int j = sp.getInt("course_jie", 10);
            editor.apply();
            String[] jc = new String[j];
            for (int i = 0; i < j; i++) {
                jc[i] = "第" + (i + 1) + "节";
            }
            final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(AddCourse.this);
            @SuppressLint("InflateParams") View view = LayoutInflater.from(AddCourse.this).inflate(R.layout.select_time, null);
            builder.setView(view);
            NumberPickerView wp_day = view.findViewById(R.id.wp_day);
            wp_day.setMaxValue(6);
            NumberPickerView wp_start = view.findViewById(R.id.wp_start);
            wp_start.setDisplayedValues(jc);
            wp_start.setMaxValue(j - 1);
            NumberPickerView wp_end = view.findViewById(R.id.wp_end);
            wp_end.setDisplayedValues(jc);
            wp_end.setMaxValue(j - 1);
            if (edit && course != null) {
                wp_day.setValue(course.getXqj() - 1);
                wp_start.setValue(StringUtil.SelectNumber(course.getJc())[0] - 1);
                wp_end.setValue(StringUtil.SelectNumber(course.getJc())[1] - 1);
            }
            Button save = view.findViewById(R.id.btn_save);
            Button btn_cancel = view.findViewById(R.id.btn_cancel);
            dialog = builder.show();
            UiUtils.setDialogWindowAttr(dialog, AddCourse.this);
            Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
            save.setOnClickListener(v1 -> {
                int day = wp_day.getValue();
                int start = wp_start.getValue() + 1;
                int end = wp_end.getValue() + 1;
                if (end >= start) {
                    String jie = start + "-" + end + "节";
                    dialog.dismiss();
                    et_time.setText(weeks[day] + " " + jie);
                } else ToastUtil.showToast("节数设置不正确！");
            });
            btn_cancel.setOnClickListener(v1 -> dialog.dismiss());
        });
        et_weeks.setOnClickListener(v -> {
            Dialog dialog;
            final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(AddCourse.this);
            @SuppressLint("InflateParams") View view = LayoutInflater.from(AddCourse.this).inflate(R.layout.select_week, null);
            builder.setView(view);
            GridView weekView = view.findViewById(R.id.PerWeekView);
            WeekAdapter myAdapter = new WeekAdapter(this, flag);
            weekView.setAdapter(myAdapter);
            TextView tv_all = view.findViewById(R.id.tv_all);
            TextView tv_type1 = view.findViewById(R.id.tv_type1);
            TextView tv_type2 = view.findViewById(R.id.tv_type2);
            if (all) tv_all.setBackground(getDrawable(R.drawable.buttonfull));
            if (dan) tv_type1.setBackground(getDrawable(R.drawable.buttonfull));
            if (shuang) tv_type2.setBackground(getDrawable(R.drawable.buttonfull));
            Button save = view.findViewById(R.id.btn_save);
            Button btn_cancel = view.findViewById(R.id.btn_cancel);
            dialog = builder.show();
            UiUtils.setDialogWindowAttr(dialog, AddCourse.this);
            Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
            weekView.setOnItemClickListener((parent, view1, position, id) -> {
                Button button = view1.findViewById(R.id.button_g);
                if (flag[position] == 0) {
                    button.setBackgroundColor(Color.WHITE);
                    flag[position] = 1;
                } else {
                    button.setBackground(getDrawable(R.drawable.btn_circle));
                    flag[position] = 0;
                }
            });

            save.setOnClickListener(v1 -> {
                dan = shuang = all = false;
                StringBuilder s = new StringBuilder("[");
                int x;
                for (int i = 0; i < flag.length; i++) {
                    if (flag[i] == 0) {
                        x = i + 1;
                        s.append(x).append(",");
                    }
                }
                s.append("]");
                s = new StringBuilder(s.toString().replace(",]", "]"));
                s = new StringBuilder(StringUtil.toZcd(s.toString()));
                et_weeks.setText(s.toString());
                if (!s.toString().contains("(")) all = true;
                dialog.dismiss();
            });
            btn_cancel.setOnClickListener(v1 -> dialog.dismiss());
            tv_type1.setOnClickListener(v1 -> {
                shuang = false;
                all = false;
                if (!dan) {
                    for (int i = 0; i < flag.length; i = i + 2) {
                        flag[i] = 0;
                        flag[i + 1] = 1;
                    }
                    weekView.setAdapter(myAdapter);
                    tv_type1.setBackground(getDrawable(R.drawable.buttonfull));
                    tv_type2.setBackgroundColor(Color.WHITE);
                    tv_all.setBackgroundColor(Color.WHITE);
                }
            });
            tv_type2.setOnClickListener(v1 -> {
                dan = false;
                all = false;
                if (!shuang) {
                    for (int i = 1; i < flag.length; i = i + 2) {
                        flag[i] = 0;
                        flag[i - 1] = 1;
                    }
                    weekView.setAdapter(myAdapter);
                    tv_type2.setBackground(getDrawable(R.drawable.buttonfull));
                    tv_type1.setBackgroundColor(Color.WHITE);
                    tv_all.setBackgroundColor(Color.WHITE);
                }
            });
            tv_all.setOnClickListener(v1 -> {
                all = !all;
                dan = false;
                shuang = false;
                if (all) {
                    for (int i = 0; i < flag.length; i++) {
                        flag[i] = 0;
                    }
                    weekView.setAdapter(myAdapter);
                    tv_all.setBackground(getDrawable(R.drawable.buttonfull));
                    tv_type1.setBackgroundColor(Color.WHITE);
                    tv_type2.setBackgroundColor(Color.WHITE);
                } else {
                    for (int i = 0; i < flag.length; i++) {
                        flag[i] = 1;
                    }
                    weekView.setAdapter(myAdapter);
                    tv_all.setBackgroundColor(Color.WHITE);
                    tv_type1.setBackgroundColor(Color.WHITE);
                    tv_type2.setBackgroundColor(Color.WHITE);
                }
            });
        });
    }

    public void toaddCourse() {
        String time = et_time.getText().toString();
        String zcd = et_weeks.getText().toString();
        String tearch = course_tearch.getText().toString();
        String name = couese_name.getText().toString();
        String room = course_room.getText().toString();
        int who = 0;
        if (!couples) who = 1;
        if (name.length() < 1)
            ToastUtil.showToast("请填写课程名！");
        else if (zcd.length() < 1)
            ToastUtil.showToast("请填写课程周数范围！");
        else if (time.length() < 1)
            ToastUtil.showToast("请填写上课时间段！");
        else {
            String[] week_js = time.split(" ");
            String week = week_js[0];
            String js = week_js[1];
            course.setXqjmc(week);
            course.setKcmc(name);
            course.setXm(tearch);
            course.setCdmc(room);
            course.setJc(js);
            course.setZcd(zcd);
            course.setXqj(StringUtil.contain_week(week));
            course.setWho(who);
            if (!edit) {
                MyApplication.getDaoInstant().getCourseDao().insertOrReplace(course);
            } else {
                MyApplication.getDaoInstant().getCourseDao().update(course);
            }
            if (couples)EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
            else EventBus.getDefault().post(new MessageEvent("SubjectFragment", 1));
            setResult(1, new Intent());
            finish();
        }
    }
}